/*
 * @lc app=leetcode.cn id=543 lang=cpp
 *
 * [543] 二叉树的直径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    int height(TreeNode* root,int Sum,int &maxVal)
    {
        if(root == NULL)
            return 0;
        
        int leftval  = 0;
        int rightval = 0;
       
        if(root->left == NULL)
        {
            leftval = 0;   
        }else
        {
            leftval = height(root->left,Sum,maxVal) + 1;
        }
        if(root->right == NULL)
        {
            rightval = 0;   
        }else
        {
            rightval = height(root->right,Sum,maxVal) + 1;
        }

        int temp = ( leftval + rightval );
        if(temp > maxVal)
            maxVal = temp;
        return max(leftval,rightval);
    }

    int diameterOfBinaryTree(TreeNode* root) {
        int max = 0;
        height(root,0,max);
        return max;
    }
};
// @lc code=end

